from fastapi import APIRouter, Depends, File, Form, UploadFile, HTTPException
from sqlalchemy.orm import Session
from pydantic import BaseModel

from services import submission_service
from db.database import get_db
from db import models


# Pydantic model for response
class SubmissionResponse(BaseModel):
    success: bool
    submission_id: int

    class Config:
        from_attributes = True


router = APIRouter()


@router.post("/", response_model=SubmissionResponse)
async def create_new_submission(
    formula_id: int = Form(...),
    image: UploadFile = File(...),
    db: Session = Depends(get_db)
):
    """
    Create a new submission by uploading an image and associating it with a formula.
    
    Args:
        formula_id: ID of the formula this submission is for
        image: Uploaded image file
        db: Database session
        
    Returns:
        Success response with submission ID
    """
    # Validate that the formula exists
    formula = db.query(models.Formula).filter(models.Formula.id == formula_id).first()
    if not formula:
        raise HTTPException(status_code=404, detail="Formula not found")
    
    # Read image data
    image_data = await image.read()
    
    # Create submission using service
    submission = submission_service.create_submission(
        db=db,
        image_data=image_data,
        filename=image.filename,
        formula_id=formula_id
    )
    
    return SubmissionResponse(success=True, submission_id=submission.id)
